//
//  JQAFNetworkTool.m
//  handworker
//
//  Created by dllo on 15/9/1.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "JQAFNetworkTool.h"
#import <AFNetworking.h>
//#import <MBProgressHUD.h>
#import <MJRefresh.h>

@implementation JQAFNetworkTool


+ (void)getUrl:(NSString *)url
       success:(void (^)(id))success
{
    [self getUrl:url body:nil result:JQJSON headerFile:nil success:success failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

+ (void)getUrl:(NSString *)url
       success:(void(^)(id result))success
       failure:(void(^)(NSError *error))failure
{
    [self getUrl:url body:nil result:JQJSON headerFile:nil success:success failure:failure];
}

+ (void)getUrl:(NSString *)url
          body:(id)body
        result:(JQResult)result
    headerFile:(NSDictionary *)headerFile
       success:(void(^)(id result))success
       failure:(void(^)(NSError *error))failure{
    // 1.获取网络请求管理类
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
////    hud.userInteractionEnabled = NO;
//    hud.labelText = @"正在加载.....";
//        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    // 3.给网络请求加个请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manger.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 4.设置返回值类型
    switch (result) {
        case JQData:
            manger.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case JQJSON:
            break;
        case JQXML:
            manger.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    // 2.设置网络请求返回值所支持的参数类型
    [manger.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/json", @"text/html", @"text/css", @"application/json", @"text/javascript", @"text/plain", nil]];
    
    NSFileManager *fileManger = [NSFileManager defaultManager];
    
    NSString *sandBoxPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *doucoment = nil;
    NSString *filePath = nil;
    if ([url hasPrefix:@"http://api.meilijia.com/app/"]) {
       doucoment = [url stringByReplacingCharactersInRange:[url rangeOfString:@"http://api.meilijia.com/app/"] withString:@""];
        filePath = [sandBoxPath stringByAppendingPathComponent:@"meilijia"];
        if (![NSKeyedUnarchiver unarchiveObjectWithFile:filePath]) {
            [fileManger createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
    }

    NSString *doucomentPath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", doucoment]];
    
    
//    // (1).获得mgr
//    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // (2).设置网络状态改变后的处理
    
    // 5.发送网络请求
    void(^block)() = ^(){
        [manger GET:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 成功回调
            if (responseObject) {
                success(responseObject);
                [NSKeyedArchiver archiveRootObject:responseObject toFile:doucomentPath];
//                 [hud setHidden:YES];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 失败回调
            if (error) {
                failure(error);
            }
        }];
    };
    NSDictionary *data = nil;
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:doucomentPath]) {
        data = [NSKeyedUnarchiver unarchiveObjectWithFile:doucomentPath];
    }
    switch (manger.reachabilityManager.networkReachabilityStatus) {
        case AFNetworkReachabilityStatusUnknown:
        case AFNetworkReachabilityStatusNotReachable:
            if (data) {
                success(data);
            }
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
        case AFNetworkReachabilityStatusReachableViaWWAN:
            block();
            break;
        default:
            break;
    }

}

+ (void)postUrl:(NSString *)url
           body:(id)body
         result:(JQResult)result
        request:(JQRequsetStyle)request
     headerFile:(NSDictionary *)headerFile
        success:(void(^)(id result))success
        failure:(void(^)(NSError *error))failure
{
    // 1.获取网络请求的管理类
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//    hud.labelText = @"正在加载.....";

    // 4.设置返回值类型
    switch (result) {
        case JQData:
            manger.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case JQJSON:
            break;
        case JQXML:
            manger.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    // 5.设置Body类型
    
    switch (request) {
        case JQRequestJSON:
            manger.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case JQRequestString:
            [manger.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError **error) {
                return parameters;
            }];
            break;
        default:
            break;
    }
    
    // 2.设置网络请求返回值所支持的参数类型
    [manger.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/json", @"text/html", @"text/css", @"application/json", @"text/javascript", @"text/plain", @"application/x-www-form-urlencoded", nil]];
    // 3.请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manger.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    
    
    
    NSFileManager *fileManger = [NSFileManager defaultManager];
    
    NSString *sandBoxPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//        NSLog(@"%@", sandBoxPath);
    NSString *doucoment = body;
    NSString *filePath = [sandBoxPath stringByAppendingPathComponent:@"meilijia"];
    if (![NSKeyedUnarchiver unarchiveObjectWithFile:filePath]) {
        [fileManger createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *doucomentPath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", doucoment]];

    
    // (1).获得mgr
//    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // (2).设置网络状态改变后的处理
    void (^block)() = ^(){
        // 6.发送请求
        [manger POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 成功回调
            if (responseObject) {
                success(responseObject);
                [NSKeyedArchiver archiveRootObject:responseObject toFile:filePath];
//                [hud setHidden:YES];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 失败回调
            if (error) {
                failure(error);
            }
        }];
    };
    
    NSDictionary *data = nil;
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:doucomentPath]) {
        data = [NSKeyedUnarchiver unarchiveObjectWithFile:doucomentPath];
    }
    
    switch (manger.reachabilityManager.networkReachabilityStatus) {
        case AFNetworkReachabilityStatusNotReachable:
            if (data) {
                success(data);
            }
            break;
        case AFNetworkReachabilityStatusUnknown:
        case AFNetworkReachabilityStatusReachableViaWiFi:
        case AFNetworkReachabilityStatusReachableViaWWAN:
            break;
        default:
            break;
    }
    
    
//    [mgr startMonitoring];
//    
//    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        // 当网络状态改变了, 就会调用这个block
//        switch (status) {
//            case AFNetworkReachabilityStatusUnknown: // 未知网络
//                NSLog(@"未知网络");
//                block();
//                break;
//                
//            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
//                NSLog(@"没有网络(断网)");
//                if (data) {
//                    success(data);
//                }
////                [hud setHidden:YES];
//                break;
//                
//            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
//                NSLog(@"手机自带网络");
//                block();
//                break;
//                
//            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
//                NSLog(@"WIFI");
//                block();
//                break;
//        }
//    }];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        [hud setHidden:YES];
//    });
//    [mgr stopMonitoring];
}


//+ (void)refreshView:(UIScrollView *)scroVillew
//                url:(NSString *)url
//               page:(NSInteger)page
//              array:(NSArray *)array
//            success:(NSArray *(^)(id result))success{
//    
// 
//    __block NSInteger bPage = page;
//    __block NSArray *bArray = array;
//    __block NSString *bUrl = url;
//    scroVillew.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        NSRange range = [bUrl rangeOfString:[NSString stringWithFormat:@"page=%ld", bPage]];
//        bUrl = [bUrl stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"page=%ld", bPage + 1]];
//        NSLog(@"%@", url);
//        [self getUrl:url success:^(id result) {
//            NSArray *arr = success(result);
//            if (arr.count) {
//                NSMutableArray *mArray = bArray.mutableCopy;
//                [mArray addObjectsFromArray:arr];
//                bArray = [NSArray arrayWithArray:mArray];
//                NSLog(@"%ld", bArray.count);
//                [scroVillew.footer endRefreshing];
//                bPage += 1;
//            } else {
//                [scroVillew.footer endRefreshingWithNoMoreData];
//            }
//        }];
//    }];
//    scroVillew.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self getUrl:url success:^(id result) {
//            NSArray *arr = success(result);
//            bArray = arr;
//            [scroVillew.header endRefreshing];
//        }];
//    }];
//    
//}


@end
